package com.xinongbest.utils;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

/**
 * @author lemonwan
 * <h1>mybatis 工具类</h1>
 */
public class MyBatisUtil {
    /**
     * 静态属性属于类，保证使用的时候全局唯一
     */
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            InputStream stream = MyBatisUtil.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
        } catch (Exception e) {
            throw new ExceptionInInitializerError(e);
        }

    }

    /**
     * <h2>打开连接</h2>
     *
     * @return SqlSession {@link SqlSession}
     */
    public static SqlSession openSession() {
        return sqlSessionFactory.openSession();
    }

    /**
     * <h2>关闭连接</h2>
     *
     * @param sqlSession {@link SqlSession}
     */
    public static void closeSession(SqlSession sqlSession) {
        if (sqlSession != null) {
            sqlSession.close();
        }
    }
}
